﻿namespace Whut.ObjectSharePointMapper.Internals
{
    using System;
    using Microsoft.SharePoint;

    public class InsertAction : SharePointAction
    {
        public SPWeb Web { get; set; }

        public InsertAction(SPWeb web, MetaDataStore metaDataStore, SessionLevelCache sessionLevelCache, EntityHydrater entityHydrater)
            : base(metaDataStore, sessionLevelCache, entityHydrater)
        {
            this.Web = web;
        }

        public TEntity Insert<TEntity>(TEntity entity)
        {
            ListInfo listInfo = this.MetaDataStore.GetListInfoFor<TEntity>();
            SPList list = this.Web.GetListByRelativeUrl(listInfo.ListRelativeUrl);
            SPListItem item = list.Items.Add();

            this.EntityHydrater.UnHydrate(entity, item);
            item.Update();
            listInfo.Id.PropertyInfo.SetValue(entity, item.ID, null);
            this.EntityHydrater.ReHydrateLookups(entity, item);

            this.SessionLevelCache.Store(item, entity);
            return entity;
        }
    }
}
